﻿//统一文件为utf-8编码编译
#pragma execution_character_set("utf-8")
///////////////////////////////////////////////////////////////////////////
// 文件名:     progressdatabase.cpp
// 描述:
// 作者:      颜磊
// 创建时间:   2024-06-08 23:43
///////////////////////////////////////////////////////////////////////////
#include "progressdatabase.h"
#include <QSqlQuery>
#include <QSqlError>
#include <QDebug>
#include <QCoreApplication>
#include <QDateTime>
#include <QUuid>
#include <QDir>

static QString guid(){
    QUuid id = QUuid::createUuid();
    QString strGuid = id.toString();
    strGuid = id.toString(QUuid::Id128);
    return strGuid;
}
static QString createMulitipleFolders(QString path){
    QDir dir(path);
    if(dir.exists(path)){
        return path;
    }
    QString parentDir = createMulitipleFolders(path.mid(0,path.lastIndexOf('/')));
    QString dirName = path.mid(path.lastIndexOf('/') + 1);
    QDir parentPath(parentDir);
    if(!dirName.isEmpty()){
        parentPath.mkdir(dirName);
    }
    return parentDir + "/" + dirName;
}

ProgressDataBase::ProgressDataBase()
{
    QString dbDir = QDir::homePath()+"/AppData/DaemonSystem";
    dbDir = "C:/Program Files/DaemonSystem/DataBase";
    createMulitipleFolders(dbDir);
    dbPath = dbDir+"/ProgressDataBase.db";
    dataBase = QSqlDatabase::addDatabase("QSQLITE",QString("connect_%1").arg(guid()));
    openDataBase();
}

ProgressDataBase::~ProgressDataBase()
{
    closeDataBase();
}

QSqlDatabase ProgressDataBase::getDataBase() const
{
    return dataBase;
}

QList<ProgressInfo> ProgressDataBase::getProgressInfoList()
{
    QList<ProgressInfo> list;
    QSqlQuery sql_query(dataBase);
    int res = -1;
    //全等查询
    if(sql_query.exec(QString("select * from ProgressInfo_table"))){
        while (sql_query.next())
        {
            ProgressInfo progressInfo;
            progressInfo.id = sql_query.value(0).toInt();
            progressInfo.setPath(sql_query.value(1).toString().toStdString());
            progressInfo.setName(sql_query.value(2).toString().toStdString());
            progressInfo.vanish_up = sql_query.value(3).toBool();
            progressInfo.cpu_use_up = sql_query.value(4).toBool();
            progressInfo.cpu_level = sql_query.value(5).toInt();
            progressInfo.heartbeat_up = sql_query.value(6).toBool();
            progressInfo.setHeartbeatMsg(sql_query.value(7).toString().toStdString());
            progressInfo.heartbeat_exit = sql_query.value(8).toBool();
            progressInfo.init_start = sql_query.value(9).toBool();
            progressInfo.init_start = sql_query.value(10).toInt();
            progressInfo.daemon_open = sql_query.value(11).toBool();
            list.append(progressInfo);
        }
    }else{
        qCritical()<< __FUNCTION__ << sql_query.lastError();
    }
    return list;
}

void ProgressDataBase::addProgressInfo(ProgressInfo progressInfo)
{
    QSqlQuery sql_query(dataBase);
    QString sqlStr = QString("insert into ProgressInfo_table(path,name,vanish_up,cpu_use_up,cpu_level,heartbeat_up,heartbeat_msg,heartbeat_exit,init_start,start_sleep,daemon_open) values('%1','%2',%3,%4,%5,%6,'%7',%8,%9,%10,%11)")
            .arg(progressInfo.path)
            .arg(progressInfo.name)
            .arg(progressInfo.vanish_up)
            .arg(progressInfo.cpu_use_up)
            .arg(progressInfo.cpu_level)
            .arg(progressInfo.heartbeat_up)
            .arg(progressInfo.heartbeat_msg)
            .arg(progressInfo.heartbeat_exit)
            .arg(progressInfo.init_start)
            .arg(progressInfo.start_sleep)
            .arg(progressInfo.daemon_open);
    if(!sql_query.exec(sqlStr)){
        qCritical()<< __FUNCTION__ << sql_query.lastError();
    }

}

void ProgressDataBase::upProgressInfo(ProgressInfo progressInfo)
{
    QSqlQuery sql_query(dataBase);
    QString sqlStr = QString("update ProgressInfo_table set "
                             "path = '%1', "
                             "name = '%2', "
                             "vanish_up = %3, "
                             "cpu_use_up = %4, "
                             "cpu_level = %5,"
                             "heartbeat_up = %6,"
                             "heartbeat_msg = '%7',"
                             "heartbeat_exit = %8,"
                             "init_start = %9,"
                             "start_sleep = %10,"
                             "daemon_open = %11 "
                             "where id=%12")
            .arg(progressInfo.path)
            .arg(progressInfo.name)
            .arg(progressInfo.vanish_up)
            .arg(progressInfo.cpu_use_up)
            .arg(progressInfo.cpu_level)
            .arg(progressInfo.heartbeat_up)
            .arg(progressInfo.heartbeat_msg)
            .arg(progressInfo.heartbeat_exit)
            .arg(progressInfo.init_start)
            .arg(progressInfo.start_sleep)
            .arg(progressInfo.daemon_open)
            .arg(progressInfo.id);
    if(!sql_query.exec(sqlStr)){
        qCritical()<< __FUNCTION__ << sql_query.lastError();
    }
}

void ProgressDataBase::delProgressInfo(uint64_t id)
{
    QSqlQuery sql_query(dataBase);
    QString sqlStr = QString("delete from ProgressInfo_table"
                             " where id=%1")
            .arg(QString::number(id));
    if(!sql_query.exec(sqlStr)){
        qCritical()<< __FUNCTION__ << sql_query.lastError();
    }
}

string ProgressDataBase::getProgressPathById(uint64_t id)
{
    string resultStr = "";
    QSqlQuery sql_query(dataBase);
    QString sqlStr = QString("select path from ProgressInfo_table where id=%1")
            .arg(QString::number(id));
    //全等查询
    if(sql_query.exec(sqlStr)){
        if (sql_query.next())
        {
            resultStr = sql_query.value(0).toString().toStdString();
        }else{
            qCritical()<< __FUNCTION__ << "not find path!" << sqlStr;
        }
    }else{
        qCritical()<< __FUNCTION__ << sql_query.lastError();
    }
    return resultStr;
}

string ProgressDataBase::getProgressNameById(uint64_t id)
{
    string resultStr = "";
    QSqlQuery sql_query(dataBase);
    QString sqlStr = QString("select name from ProgressInfo_table where id=%1")
            .arg(QString::number(id));
    //全等查询
    if(sql_query.exec(sqlStr)){
        if (sql_query.next())
        {
            resultStr = sql_query.value(0).toString().toStdString();
        }else{
            qCritical()<< __FUNCTION__ << "not find path!" << sqlStr;
        }
    }else{
        qCritical()<< __FUNCTION__ << sql_query.lastError();
    }
    return resultStr;
}

void ProgressDataBase::openDataBase()
{
    dataBase.setDatabaseName(dbPath);
    dataBase.open();

    QSqlQuery sql_query(dataBase);
    if(!sql_query.exec("select * from ProgressInfo_table")){
        if(!sql_query.exec("create table ProgressInfo_table("
                           "id integer primary key,"
                           "path text,"
                           "name text,"
                           "vanish_up bool,"
                           "cpu_use_up bool,"
                           "cpu_level integer,"
                           "heartbeat_up bool,"
                           "heartbeat_msg text,"
                           "heartbeat_exit bool,"
                           "init_start bool,"
                           "start_sleep int,"
                           "daemon_open bool,"
                           "enabled bool,"
                           "cpu_use_now integer,"
                           "memory_usage integer,"
                           "io_read integer,"
                           "io_write integer)"))
            qCritical()<< __FUNCTION__ << sql_query.lastError();
    }
}

void ProgressDataBase::closeDataBase()
{
    if(dataBase.isOpen())
        dataBase.close();
}
